<script setup>
import { ref,onMounted } from 'vue'
import { queryAllClazzApi } from '@/api/clazz'
import { queryStuApi,addStuApi,queryByIdApi,updateStuApi,deleteStuApi } from '@/api/stu'
import { ElMessage,ElMessageBox } from 'element-plus'


const currentPage = ref(1)
const pageSize = ref(10)
const handleSizeChange = (val) => {
  search();
}
const handleCurrentChange = (val) => {
  search();
}
const total = ref(0)

const searchStu = ref({
  name: '',
  degree: '',
  clazzId: ''
})

onMounted(() => {
  queryClazzs();
  search();
})

const search = async() => {
  const result = await queryStuApi(searchStu.value.name,
                                  searchStu.value.degree,
                                  searchStu.value.clazzId,
                                  currentPage.value,
                                  pageSize.value);
  if(result.code){
    stuList.value = result.data.rows;
    total.value = result.data.total;
  }
}

const clazzs = ref([])
const queryClazzs = async() => {
   const result = await queryAllClazzApi();
   if(result.code){
     clazzs.value = result.data;
   }
}


const degrees = ([{ name: '初中', value: 1 }, { name: '高中', value: 2 },
                  { name: '大专', value: 3 },{ name: '本科', value: 4 },
                  { name: '硕士', value: 5 },{ name: '博士', value: 6 }])

const genders = ref([{ name: '男', value: 1 }, { name: '女', value: 2 }]); 

const colleges = ref([{ name: '是', value: 1 }, { name: '否', value: 0 }]); 

const stuList = ref([])

const student = ref({
  no: '',
  name: '',
  gender: '',
  phone: '',
  degree: '',
  clazzId: '',
  isCollege: '',
  idCard: '',
  address: '',
  graduationDate: ''
})

const dialogVisible = ref(false)
const dialogTitle = ref('')

const insertStu = () =>{
  dialogVisible.value = true;
  dialogTitle.value = '新增学员';
  student.value = {
  no: '',
  name: '',
  gender: '',
  phone: '',
  degree: '',
  clazzId: '',
  isCollege: '',
  idCard: '',
  address: '',
  graduationDate: ''
}
if(studentFormRef.value){
      studentFormRef.value.resetFields();
  }
}

const selectById = async(id) => {
  const result = await queryByIdApi(id);
  if(result.code){
    dialogVisible.value = true;
    student.value = result.data;
    dialogTitle.value = '修改学员信息';
    if(studentFormRef.value){
      studentFormRef.value.resetFields();
  }
  }
}

//表单校验
const studentFormRef = ref();
//表单校验规则
const rules = ref({
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { min: 2, max: 10, message: '用户名长度应在2到10个字符之间', trigger: 'blur' }
  ],
  no: [
    { required: true, message: '请输入学号', trigger: 'blur' },
    { pattern: /^\d{10}$/, message: '学号长度应为10位数字', trigger: 'blur' }
  ],
  gender: [
    { required: true, message: '请选择性别', trigger: 'change' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号', trigger: 'blur' } //正则表达式 : ^ 开头，$ 结尾, \d 匹配数字
  ],
  idCard: [
    { required: true, message: '请输入身份证号', trigger: 'blur' },
    { pattern: /(^\d{15}$)|(^\d{17}[\dXx]$)/, message: '请输入有效的身份证号', trigger: 'blur' } //正则表达式 : ^ 开头，$ 结尾, \d 匹配数字
  ],
  isCollege: [
    { required: true, message: '请选择院校', trigger: 'change' }
  ],
});

const save = async () => {
  if (!studentFormRef) return
  await studentFormRef.value.validate(async (valid, fields) => {
    if (valid) {//通过
      let result;
      if(student.value.id){
        result = await updateStuApi(student.value);
      }else{
         result = await addStuApi(student.value);
      }
      if (result.code) {
        dialogVisible.value = false;
        ElMessage.success('保存成功');
        search();
      } else {
        ElMessage.error(result.msg);
      }
    } else {//不通过
      ElMessage.error('表单效验不通过,请检查表单');
    }
  });
}

const deleteById = async (id) => {
  ElMessageBox.confirm(
    '你确定要删除该员工吗?',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then( async() => {
     const result = await deleteStuApi(id);
     if(result.code){
      ElMessage.success('删除成功');
      search();
     }else{
      ElMessage.error(result.msg);
     }
    })
    .catch(() => {
      ElMessage.info('已取消删除')
    })
}

const selectIds = ref([])
const handleSelectionChange = (val) => {
  selectIds.value = val.map(item => item.id);
}

const deleteByIds = () => {
  ElMessageBox.confirm(
    '你确定要删除这些员工数据吗?',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then( async() => {
     const result = await deleteStuApi(selectIds.value);
     if(result.code){
      ElMessage.success('删除成功');
      search();
     }else{
      ElMessage.error(result.msg);
     }
    })
    .catch(() => {
      ElMessage.info('已取消删除')
    })
}
</script>

<template>
  <h1>学员管理</h1>
  {{searchStu}}
  <!-- 搜索框 -->
  <el-form :inline="true" :model="searchStu" class="demo-form-inline">
    <el-form-item label="姓名">
      <el-input v-model="searchStu.name" placeholder="请输入班级名称"/>
    </el-form-item>

    <el-form-item label="最高学历">
      <el-select v-model="searchStu.degree" placeholder="请选择">
        <el-option v-for="degree in degrees"  :label="degree.name" :value="degree.value" />
      </el-select>
    </el-form-item>

    <el-form-item label="所属班级">
      <el-select v-model="searchStu.clazzId" placeholder="请选择">
        <el-option v-for="clazz in clazzs"  :label="clazz.name" :value="clazz.id" />
      </el-select>
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="search">查询</el-button>
      <el-button type="info" @click="clear">清空</el-button>
    </el-form-item>
  </el-form>

  <!-- 新增or批量删除按钮 -->
  <div class="button">
    <el-button type="primary" @click="insertStu">添加学员</el-button>
    <el-button type="danger" @click="deleteByIds">批量删除</el-button>
  </div>

  <!-- 表格 -->
  <el-table :data="stuList" border style="width: 100%" @selection-change="handleSelectionChange">
    <el-table-column type="selection" width="50" align="center" />
    <el-table-column prop="name" label="姓名" width="80" align="center" />
    <el-table-column prop="no" label="学号" width="120" align="center" />
    <el-table-column prop="clazzName" label="班级" width="200" align="center" />
    <el-table-column prop="gender" label="性别" width="100" align="center">
      <template #default="scope">
        {{ scope.row.gender === 1 ? '男' : '女' }}
      </template>
    </el-table-column>
    <el-table-column prop="phone" label="手机号" width="150" align="center" />
    <el-table-column prop="degree" label="最高学历" width="100" align="center">
      <template #default="scope">
        <span v-if="scope.row.degree == 1">初中</span>
        <span v-else-if="scope.row.degree == 2">高中</span>
        <span v-else-if="scope.row.degree == 3">大专</span>
        <span v-else-if="scope.row.degree == 4">本科</span>
        <span v-else-if="scope.row.degree == 5">硕士</span>
        <span v-else-if="scope.row.degree == 6">博士</span>
      </template>
    </el-table-column>
    <el-table-column prop="violationCount" label="违纪次数" width="100" align="center" />
    <el-table-column prop="violationScore" label="违纪扣分" width="100" align="center" />
    <el-table-column prop="updateTime" label="最后操作时间" width="200" align="center" />
    <el-table-column label="操作" align="center">
      <template #default="scope">
        <el-button type="primary" size="small" @click="selectById(scope.row.id)">编辑</el-button>
        <el-button type="danger" size="small" @click="ScoreById(scope.row.id)">违纪</el-button>
        <el-button type="danger" size="small" @click="deleteById(scope.row.id)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>
  <br>

<!-- 分页 -->
<el-pagination     v-model:current-page="currentPage" 
                   v-model:page-size="pageSize"
                   :page-sizes="[10, 20, 50, 100]"
                   layout="total, sizes, prev, pager, next, jumper"
                   :total="total" 
                   @size-change="handleSizeChange"
                   @current-change="handleCurrentChange" />

<el-dialog v-model="dialogVisible" :title="dialogTitle">
    {{ student }}
    <el-form :model="student" :rules="rules" ref="studentFormRef" label-width="80px">
      <!-- 基本信息 -->
      <!-- 第一行 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="姓名" prop="name">
            <el-input v-model="student.name" placeholder="请输入姓名"></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="学号" prop="no">
            <el-input v-model="student.no" placeholder="请输入学号"></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第二行 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="性别" prop="gender">
            <el-select v-model="student.gender" placeholder="请选择性别" style="width: 100%;">
              <el-option v-for="gender in genders" :label="gender.name" :value="gender.value" />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="手机号" prop="phone">
            <el-input v-model="student.phone" placeholder="请输入员工手机号"></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第三行 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="身份证号" prop="idCard">
            <el-input v-model="student.idCard" placeholder="请输入身份证号"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="是否院校毕业" prop="isCollege">
            <el-select v-model="student.isCollege" placeholder="请选择" style="width: 100%;">
              <el-option v-for="college in colleges" :label="college.name" :value="college.value" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第四行 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="联系地址">
            <el-input v-model="student.address" placeholder="请输入联系地址"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="最高学历">
            <el-select v-model="student.degree" placeholder="请选择" style="width: 100%;">
              <el-option v-for="degree in degrees" :label="degree.name" :value="degree.value" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第五行 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="毕业时间">
            <el-date-picker v-model="student.graduationDate" type="date" style="width: 100%;" placeholder="请选择毕业时间"
              format="YYYY-MM-DD" value-format="YYYY-MM-DD"></el-date-picker>
          </el-form-item>
        </el-col>
          <el-col :span="12">
          <el-form-item label="所属班级">
            <el-select v-model="student.clazzId" placeholder="请选择" style="width: 100%;">
              <el-option v-for="clazz in clazzs"  :label="clazz.name" :value="clazz.id" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <!-- 底部按钮 -->
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="save">保存</el-button>
      </span>
    </template>
</el-dialog>
</template>
<style scoped>
.button{
  margin: 20px;
}
.demo-form-inline .el-input {
  --el-input-width: 220px;
}

.demo-form-inline .el-select {
  --el-select-width: 220px;
}
</style>